package com.itboye.lottery.activity;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.itboye.bylibrary.util.ScreenUtil;
import com.itboye.lottery.R;
import com.itboye.lottery.activity.daletou.BascketballMainActivity;
import com.itboye.lottery.adapter.LqBetListAdapter;
import com.itboye.lottery.alert.ByAlert;
import com.itboye.lottery.base.BaseActivity;
import com.itboye.lottery.bean.FootballMatchBean;
import com.itboye.lottery.bean.OrderBean;
import com.itboye.lottery.bean.ZqBetListItem;
import com.itboye.lottery.bean.ZqMatchDataCheck;
import com.itboye.lottery.callback.PayCallBack;
import com.itboye.lottery.dialog.PayDialog;
import com.itboye.lottery.enums.LotteryType;
import com.itboye.lottery.presenter.UserPresenter;
import com.itboye.lottery.retrofit.ResponseCallback;
import com.itboye.lottery.utils.ConstUrl;
import com.itboye.lottery.view.FlowLayout;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.BindView;

import static com.itboye.lottery.utils.Combination.getVoteNums;
import static com.itboye.lottery.utils.GsonUtil.getSkipIdAndGroupIdGson;

public class LqBetListActivity extends BaseActivity implements ResponseCallback, CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.rv_touzhu_list)
    RecyclerView rv_touzhu_list;
    @BindView(R.id.ll_passtype)
    LinearLayout ll_passtype;
    TextView tv_bottom_1, tv_bottom_sure;
    EditText tv_bottom_beishu_multiple;
    HashMap<String, HashMap<String, String>> map = new LinkedHashMap<>();
    private int page;
    ArrayList<ZqBetListItem> zqBetListItemArrayList = new ArrayList<>();
    LqBetListAdapter adapter;
    ImageView iv_bottom_reduce_multiple, iv_bottom_increase_multiple;
    //    LinearLayout ll_passtype_line1, ll_passtype_line2;
    //    int lotType = 3011;
    UserPresenter userPresenter = new UserPresenter(this);
    ArrayList<FootballMatchBean> footballMatchBeanArrayList = new ArrayList<>();
    private JSONObject jsonParent;
    JSONObject jsonObjectChild = new JSONObject();
    private int voteNum = 0;
    TextView tv_bottom_total;
    private StringBuilder stringBuilder;
    HashMap<String, Boolean> hashMap = new HashMap<>();
    private String buyType = "";
    LotteryType lotteryType;
    private int multiple;
    private String passType;
    TextView tv_jixuan_5;
    boolean isDg;
    FlowLayout fl_pass_type;
    CheckBox cb_agree_xieyi;
    private float totalMoney;


    public static LqBetListActivity activity;
    private String origin_num;

    TextView tv_bottom_faqigendan;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_lq_bet_list;
    }

    @Override
    protected void initData() {
        jsonParent = new JSONObject();
        map = (HashMap<String, HashMap<String, String>>) getIntent().getSerializableExtra("map");
        page = getIntent().getIntExtra("pager", 0);
        setTitle(getResources().getStringArray(R.array.jclq_types_name_list)[page]);
        zqBetListItemArrayList = (ArrayList<ZqBetListItem>) getIntent().getSerializableExtra("arrayList");
        footballMatchBeanArrayList = (ArrayList<FootballMatchBean>) getIntent().getSerializableExtra("old_arrayList");
        isDg = getIntent().getBooleanExtra("isDg", false);
        lotteryType = (LotteryType) getIntent().getSerializableExtra("lotteryType");
//        tv_bottom_faqigendan.setVisibility(View.GONE);
        initPassType();
        rv_touzhu_list.setLayoutManager(new LinearLayoutManager(this));
        rv_touzhu_list.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        adapter = new LqBetListAdapter(this, zqBetListItemArrayList);
        adapter.setPager(page);
        adapter.setOldArrayList(footballMatchBeanArrayList);
        rv_touzhu_list.setAdapter(adapter);
        tv_bottom_beishu_multiple.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                caculateVoteNums();
            }
        });
        Log.v("", map + "");
    }

    private void initPassType() {
        int width = ScreenUtil.getScreenWidth(this);
        int passIndex = 0;
        for (int i = 0; i < (isDg ? zqBetListItemArrayList.size() : zqBetListItemArrayList.size() - 1); i++) {
            CheckBox checkBox = new CheckBox(this);
            passIndex++;
            String key = "";
            if (i == 0 && isDg) {
                checkBox.setText("单关");
                key = "1*1";
            } else {
                checkBox.setText((!isDg ? (passIndex + 1) : passIndex) + "串1");
                key = checkBox.getText().toString().replace("串", "*");
            }
            checkBox.setButtonDrawable(null);
            checkBox.setBackgroundResource(R.drawable.red_gray_selecter);
            checkBox.setTextColor(ContextCompat.getColorStateList(this, R.color.gray_white_selector));
            checkBox.setGravity(Gravity.CENTER);
            checkBox.setTag(key);
            boolean isChecked = i == zqBetListItemArrayList.size() - (isDg ? 1 : 2);
            hashMap.put(key, isChecked);
            checkBox.setChecked(isChecked);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams((width - 12 * 4) / 4, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(6, 6, 6, 6);
            checkBox.setOnCheckedChangeListener(this);
            fl_pass_type.addView(checkBox, layoutParams);
        }
        stringBuilder = new StringBuilder(zqBetListItemArrayList.size() + "*1");
        buyType = stringBuilder.toString();
        caculateVoteNums();
    }

    private void caculateVoteNums() {
        if (buyType.isEmpty()) {
            tv_bottom_1.setText("过关方式");
            voteNum = 0;
        } else {
            if (buyType.equals("1*1")) {
                tv_bottom_1.setText("单关");
            } else {
                tv_bottom_1.setText(buyType.replaceAll("\\*", "串"));
            }
            this.buyType = buyType;
            voteNum = getVoteNums(zqBetListItemArrayList, buyType);
        }
        multiple = Integer.parseInt(TextUtils.isEmpty(tv_bottom_beishu_multiple.getText().toString()) ? "0" : tv_bottom_beishu_multiple.getText().toString());
        totalMoney = 2 * voteNum * multiple;
        setVoteAndMultipleAndMoney(voteNum, multiple, totalMoney);
    }

    public void faQiGenDan() {
        if (!cb_agree_xieyi.isChecked()) {
            ByAlert.alert("请先同意服务协议");
            return;
        }
        getRequestParams();
        //发起跟单
        startActivity(new Intent(this, FaQiGenDanActivity.class)
                .putExtra("hash", zqBetListItemArrayList)
                .putExtra("lottery_type", lotteryType)
                .putExtra("single_money", zqBetListItemArrayList)
                .putExtra("pass_type", buyType)
                .putExtra("multiple", multiple)
                .putExtra("passType", passType)
                .putExtra("ball_type", 2)//2：篮球  1：足球
                .putExtra("num", jsonParent.toString())
                .putExtra("total_money", voteNum * 2));
    }

    public void toXieYi(View view) {
        startActivity(new Intent(this, WebActivity.class).putExtra("title", "服务协议").putExtra("url", ConstUrl.SERVICE_XIEYI));
    }

    //跳转奖金优化
    public void bonusOpti(View view) {
        ByAlert.alert("正在升级中，敬请期待");

//        if (Integer.valueOf(tv_bottom_beishu_multiple.getText().toString()) <= 0) {
//            ByAlert.alert("倍数不能小于1");
//            return;
//        }
//        if (tv_bottom_1.getText().toString().equals("过关方式")) {
//            ByAlert.alert("请选择过关方式");
//            return;
//        }
//        if (!cb_agree_xieyi.isChecked()) {
//            ByAlert.alert("请先同意服务协议");
//            return;
//        }
//        getRequestParams();
//        startActivity(new Intent(this, BonusOptimizationActivity.class)
//                .putExtra("map", map)
//                .putExtra("multiple", multiple)
//                .putExtra("free_pass", passType)
//                .putExtra("totalMoney", totalMoney)
//
//                .putExtra("pass_type", buyType)
//                .putExtra("lottery_type", lotteryType)
//                .putExtra("voteNum", voteNum)
//                .putExtra("total_money", voteNum * 2)
//                .putExtra("type",LotteryType.JCLQ)
//
//                .putExtra("num", jsonParent.toString())
//                .putExtra("array", zqBetListItemArrayList)
//        );
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_bottom_1:
                showPassType();
                break;
            case R.id.item_zqbet_list_delete:
                int position = (int) view.getTag();
                zqBetListItemArrayList.remove(position);
                adapter.notifyDataSetChanged();
                break;
            case R.id.iv_bottom_reduce_multiple:
                if (Integer.valueOf(tv_bottom_beishu_multiple.getText().toString()) > 1) {
                    tv_bottom_beishu_multiple.setText("" + (Integer.valueOf(tv_bottom_beishu_multiple.getText().toString()) - 1));
//                    setTotalMultibalAndBetZhuShuAndMoney();
                }
                break;
            case R.id.iv_bottom_increase_multiple:
                if (Integer.valueOf(tv_bottom_beishu_multiple.getText().toString()) < 100) {
                    tv_bottom_beishu_multiple.setText("" + (Integer.valueOf(tv_bottom_beishu_multiple.getText().toString()) + 1));
//                    setTotalMultibalAndBetZhuShuAndMoney();
                }
                break;
            case R.id.tv_bottom_sure:
                if (Integer.valueOf(tv_bottom_beishu_multiple.getText().toString()) <= 0) {
                    ByAlert.alert("倍数不能小于1");
                    return;
                }
                if (tv_bottom_1.getText().toString().equals("过关方式")) {
                    ByAlert.alert("请选择过关方式");
                    return;
                }
                if (!cb_agree_xieyi.isChecked()) {
                    ByAlert.alert("请先同意服务协议");
                    return;
                }
                getRequestParams();
                //先调用篮球校验接口 生成num请求参数  待完成
                origin_num = jsonParent.toString();
                userPresenter.getBasketballMathDataCheck(origin_num, multiple, passType);
                break;
            case R.id.tv_jixuan_5:
                finish();
//                startActivity(new Intent(this, FootballMainActivity.class));
                break;
            case R.id.tv_bottom_faqigendan:
                faQiGenDan();
                break;
        }
    }

    private void getRequestParams() {
        //开始构造数据
        // 3010: 胜平负
        // 3006:让球胜平负
        // 3007: 全场比分(90分钟)
        // 3008: 进球数
        // 3009: 半全场胜负  这个暂时不支持
        // 3011: 混合过关 （一注投注中包含2个玩法以上的就是混合过关）
        String num = "";
        multiple = Integer.parseInt(tv_bottom_beishu_multiple.getText().toString());
        passType = "1,2";
        StringBuffer stringBuffer = new StringBuffer();
        if (!tv_bottom_1.getText().toString().contains(",")) {
            if (tv_bottom_1.getText().toString().equals("单关")) {
                passType = "1";
            } else {
                passType = (tv_bottom_1.getText().toString().substring(0, 1));
            }
        } else {
            String pass[] = tv_bottom_1.getText().toString().split(",");
            for (String s : pass) {
                stringBuffer.append(s.substring(0, 1) + ",");
            }
            if (stringBuffer.toString().endsWith(",")) {
                passType = stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1);
            } else {
                passType = stringBuffer.toString();
            }
        }
        if (passType.isEmpty()) {
            ByAlert.alert("请选择过关方式");
            return;
        }
        jsonObjectChild = new JSONObject();
        jsonParent = new JSONObject();
        switch (page) {
            case 0://混投的
                buildSfBetData(false, 3001);
                buildSfBetData(true, 3002);
                buildDxfBetData(3004);
                buildSfcBetData(3003);
                break;
            case 1://胜负
                buildSfBetData(true, 3001);
                break;
            case 2://让分胜负
                buildSfBetData(false, 3002);
                break;
            case 3://大小分
                buildDxfBetData(3004);
                break;
            case 4://胜负差
                buildSfcBetData(3003);
                break;
        }
        Log.v("bet_params", "投注 data  " + jsonParent.toString());
    }

    private String buildHunTouBetData() {
        return null;
    }

    private String buildSfcBetData(int lotType) {
        for (int i = 0; i < zqBetListItemArrayList.size(); i++) {
            ZqBetListItem zqBetListItem = zqBetListItemArrayList.get(i);
            if (zqBetListItem.getSfcList().size() > 0) {
                if (zqBetListItem.getSfcList().size() > 0) {
                    String date = zqBetListItem.getDate();
                    String num = zqBetListItem.getNum();
                    int single = zqBetListItem.getSingle();
                    try {
                        JSONObject jsonObjectChildInner = new JSONObject();
                        for (ZqBetListItem.SpfBean spfBean : zqBetListItem.getSfcList()) {
                            String key = spfBean.getKey();
                            String value = spfBean.getValue();
                            if (key.endsWith("3")) {
                                if (key.startsWith("1-5")) {
                                    key = "w1";
                                } else if (key.startsWith("6-10")) {
                                    key = "w2";
                                } else if (key.startsWith("11-15")) {
                                    key = "w3";
                                } else if (key.startsWith("16-20")) {
                                    key = "w4";
                                } else if (key.startsWith("21-25")) {
                                    key = "w5";
                                } else if (key.startsWith("26+")) {
                                    key = "w6";
                                }
                            } else {
                                if (key.startsWith("1-5")) {
                                    key = "l1";
                                } else if (key.startsWith("6-10")) {
                                    key = "l2";
                                } else if (key.startsWith("11-15")) {
                                    key = "l3";
                                } else if (key.startsWith("16-20")) {
                                    key = "l4";
                                } else if (key.startsWith("21-25")) {
                                    key = "l5";
                                } else if (key.startsWith("26+")) {
                                    key = "l6";
                                }
                            }
                            jsonObjectChildInner.put(key, value);
                        }
                        JSONObject jsonObjectChild = new JSONObject();
                        jsonObjectChildInner.put("single", single);
                        jsonObjectChild.put(lotType + "", jsonObjectChildInner);
                        String key = date.replaceAll("-", "") + num;
                        if (jsonParent.has(key)) {
                            jsonParent.getJSONObject(key).put(lotType + "", jsonObjectChildInner);
                        } else {
                            jsonParent.put(key, jsonObjectChild);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        Log.v("bet_params", jsonParent.toString() + "--------\n" + lotType);
        return jsonParent.toString();
    }


    private String buildDxfBetData(int lotType) {
        for (int i = 0; i < zqBetListItemArrayList.size(); i++) {
            ZqBetListItem zqBetListItem = zqBetListItemArrayList.get(i);
            if (zqBetListItem.getDxfList().size() > 0) {
                String date = zqBetListItem.getDate();
                String num = zqBetListItem.getNum();
                int single = zqBetListItem.getSingle();
                try {
                    JSONObject jsonObjectChildInner = new JSONObject();
                    for (ZqBetListItem.SpfBean spfBean : zqBetListItem.getDxfList()) {
                        jsonObjectChildInner.put("score", spfBean.getOtherData());//预估分
                        jsonObjectChildInner.put(spfBean.getKey().equals("大分") ? "1" : "0", spfBean.getValue());//大小分
                    }
                    JSONObject jsonObjectChild = new JSONObject();
                    jsonObjectChildInner.put("single", single);
                    jsonObjectChild.put(lotType + "", jsonObjectChildInner);
                    String key = date.replaceAll("-", "") + num;
                    if (jsonParent.has(key)) {
                        jsonParent.getJSONObject(key).put(lotType + "", jsonObjectChildInner);
                    } else {
                        jsonParent.put(key, jsonObjectChild);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        Log.v("bet_params", jsonParent.toString() + "--------\n" + lotType);
        return jsonParent.toString();
    }

    private JSONObject buildSfBetData(boolean isSpf, int lotType) {
        for (int i = 0; i < zqBetListItemArrayList.size(); i++) {
            jsonObjectChild = new JSONObject();
            ZqBetListItem zqBetListItem = zqBetListItemArrayList.get(i);
            if ((isSpf ? zqBetListItem.getRfsfList() : zqBetListItem.getFrsfList()).size() > 0) {
                String date = zqBetListItem.getDate();
                String num = zqBetListItem.getNum();
                int single = zqBetListItem.getSingle();
                try {
                    JSONObject jsonObjectChildInner = new JSONObject();
//            ArrayList<String> arrayList = new ArrayList<>();
                    for (ZqBetListItem.SpfBean spfBean : (isSpf ? zqBetListItem.getRfsfList() : zqBetListItem.getFrsfList())) {
                        if (spfBean.getKey().equals("主胜")) {
                            jsonObjectChildInner.put("3", spfBean.getValue());
                        } else if (spfBean.getKey().equals("平")) {
                            jsonObjectChildInner.put("1", spfBean.getValue());
                        } else if (spfBean.getKey().equals("客胜")) {
                            jsonObjectChildInner.put("0", spfBean.getValue());
                        }
//                arrayList.add();
                    }
                    jsonObjectChildInner.put("single", single);
//                jsonObjectChildInner.put("goals", new Gson().toJson(arrayList));
                    jsonObjectChild.put(lotType + "", jsonObjectChildInner);
                    String dateTemp = date.replaceAll("-", "") + num;
                    if (jsonParent.has(dateTemp)) {
                        jsonParent.getJSONObject(dateTemp).put(lotType + "", jsonObjectChildInner);
                    } else {
                        jsonParent.put(dateTemp, jsonObjectChild);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        Log.v("bet_params", jsonParent.toString() + "--------\n" + lotType);
        return jsonParent;
    }

    private void showPassType() {
        if (ll_passtype.getVisibility() == View.VISIBLE) {
            ll_passtype.setVisibility(View.GONE);
            tv_bottom_1.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.d0, 0);
        } else {
            ll_passtype.setVisibility(View.VISIBLE);
            tv_bottom_1.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.cz, 0);
        }
    }

    public void touzhu(View view) {

    }

    public void clearAllChecked(View view) {
        zqBetListItemArrayList.clear();
        adapter.notifyDataSetChanged();
        BascketballMainActivity.Companion.getActivity().clearSelctCache();
        BascketballMainActivity.Companion.getActivity().notifyData();
        setVoteAndMultipleAndMoney(0, multiple, 0);
    }


    private void setVoteAndMultipleAndMoney(int voteNum, int multiple, float totalMoney){
        tv_bottom_total.setText(Html.fromHtml(String.format("共%1s注%2s倍&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font color='red'>%.2f元</font>", voteNum, multiple, totalMoney)));
    }

    @Override
    public void success(@NotNull Object o, @NotNull String requestSuccessType) {
        if (requestSuccessType == userPresenter.lqCreateOrder_SUCCESS) {
            OrderBean orderBean = (OrderBean) o;
            PayDialog payDialog = new PayDialog(this, true);
            payDialog.setOrderBean(orderBean);
            payDialog.setCallBack(new PayCallBack() {
                @Override
                public void paySuccess() {
                    finish();
                }

                @Override
                public void payFail(String msg) {

                }
            });
            payDialog.show();
        } else if (requestSuccessType == userPresenter.getBasketballMathDataCheck_SUCCESS) {
            ZqMatchDataCheck zqMatchDataCheck = (ZqMatchDataCheck) o;
            String num = getSkipIdAndGroupIdGson().toJson(zqMatchDataCheck.getList());
            userPresenter.lqCreateOrder(num, origin_num, multiple, passType);
        }
    }

    @Override
    public void fail(int code, @NotNull Object msg, @NotNull String requestErrorType) {
        if (requestErrorType == userPresenter.lqCreateOrder_FAIL) {
            ByAlert.alert(msg);
        }
        if (requestErrorType == userPresenter.getBasketballMathDataCheck_FAIL) {
            ByAlert.alert(msg);
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        String tag = compoundButton.getTag() + "";
        hashMap.put(tag, b);
        stringBuilder = new StringBuilder();
        Iterator<Map.Entry<String, Boolean>> keyset = hashMap.entrySet().iterator();
        while (keyset.hasNext()) {
            Map.Entry entry = (Map.Entry) keyset.next();
            String key = entry.getKey() + "";
            boolean value = hashMap.get(key);
            if (value) {
                stringBuilder.append(key + ",");
            }
        }
        Log.v("passtype", stringBuilder.toString());
        if (stringBuilder.toString().length() > 0) {
            buyType = stringBuilder.toString().substring(0, stringBuilder.length() - 1);
            caculateVoteNums();
        } else {
            try {
                buyType = "";
                caculateVoteNums();
            } catch (Exception e) {

            }
        }
    }
}
